package org.zezs.sync.mongo.config.mongo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zezs.sync.mongo.Constants;
import org.zezs.sync.mongo.utils.InputStreamUtil;
import org.zezs.sync.mongo.utils.SSHTunnul;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MongoUtil {
    public static Map<String, MongoConfig> map = new HashMap<>();

    static Logger logger = LoggerFactory.getLogger(MongoUtil.class);

    public static MongoDatabase getMongoDb(String source) {
        MongoConfig mongoEnt = map.get(source);
        if (mongoEnt == null) {
            return null;
        }
        return mongoEnt.getMongoClient().getDatabase(mongoEnt.getDatabase());
    }

    /**
     * 初始化mongo数据连接
     */
    public static void init() {
        InputStream resourceAsStream = MongoUtil.class.getResourceAsStream(Constants.mondbfile);
        try {
            byte[] copyToByteArray = InputStreamUtil.readAll(Constants.mondbfile);
            List<MongoConfig> parse = JSONArray.parseArray(new String(copyToByteArray, "utf-8"), MongoConfig.class);
            for (int i = 0; i < parse.size(); i++) {
                MongoConfig mongoEnt = parse.get(i);
                if (mongoEnt.isUse()) {
                    //代理配置初始化
                    Proxy proxy = mongoEnt.getProxy();
                    if(null!=proxy){
                        SSHTunnul.open(proxy.getSshHost(), proxy.getSshAccount(), proxy.getSshPwd(), proxy.getDestHost(), proxy.getDestPort(),proxy.getLocalPort());
                    }
                    MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoEnt.getUri()));
                    mongoEnt.setMongoClient(mongoClient);
                    map.put(mongoEnt.getSource(), mongoEnt);
                }
            }
            logger.info(JSON.toJSONString(map.keySet(), true));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
